clear all
global system "linux"

if "${system}" == "linux" {
	
	global code "/"
	global s "/"
}

run "${code}${s}_set-path.do"

use "${temp}/embs-417k.dta", clear // _jumbo-confidence_levelorming-dataprep.do

gen notba = tbaelig ==0

keep if inrange(orig_ym, ym(2009, 1), ym(2012, 12))
drop if agency_id ==1 & orig_ym <= ym(2011, 10)
keep if orig_loan_amount > 417000

egen seller_id_id = group(seller_id)
egen state_id_id = group(state_id)

sort state_id orig_ym seller_id_id
foreach fn in max min {
	by state_id orig_ym seller_id_id: egen `fn'_tba = `fn'(tbaelig)
}
gen balanced = max_tba == 1 & min_tba == 0

global controls "c.credit_score##c.credit_score##c.credit_score c.mtoi##c.mtoi##c.mtoi *Orig"
global FEs "state_id_id orig_ym seller_id_id LLPAbin"



*** regression

reghdfe orig_rate notba c.orig_loan_amount##c.orig_loan_amount##c.orig_loan_amount c.orig_loan_to_value##c.orig_loan_to_value##c.orig_loan_to_value $controls, a(LLPAbin orig_ym) vce(robust)
estimate save "${Estimates}/within-high-balance-1", replace

reghdfe orig_rate notba c.orig_loan_amount##c.orig_loan_amount##c.orig_loan_amount c.orig_loan_to_value##c.orig_loan_to_value##c.orig_loan_to_value $controls, a(LLPAbin orig_ym state_id_id) vce(robust)
estimate save "${Estimates}/within-high-balance-2", replace

reghdfe orig_rate notba c.orig_loan_amount##c.orig_loan_amount##c.orig_loan_amount c.orig_loan_to_value##c.orig_loan_to_value##c.orig_loan_to_value $controls, a($FEs) vce(robust)
estimate save "${Estimates}/within-high-balance-3", replace


// tables
run _esttab-latex-options.do
label var notba "NoTBA"
eststo clear
foreach n of numlist 1/3 {
	estimate use "${Estimates}/within-high-balance-`n'"
	eststo
	
	estadd local ym "Y"
	estadd local control "Y"
	if `n' >= 2 estadd local state_id "Y"
	if `n' >= 3 estadd local lender "Y"		
}

esttab using "${table}/reg-within-high-balance.tex", replace nomtitle keep(notba) ///
 ${opts_esttab}  b(%9.3fc) se(%9.3f) star(* 0.10 ** 0.05 *** 0.01) ///
 stats(ym state_id lender control N r2_a, fmt(%1s %1s %1s %1s %9.0fc %3.2f) ///
 labels("Month FE" "State FE" "Lender FE" "Other Controls" "\midrule N. Obs." "Adj. $ R^2$"))



*** Summary stats
eststo clear
local mtitle
foreach n in 0 1 {
	eststo : qui estpost su  orig_loan_amount homeprice orig_loan_to_value credit_score mtoi *Orig if balanced==1 & tbaelig == `n'
	
	if `n' == 0 local mtitle "`mtitle' `"TBA-ineligible MBS"'"
	if `n' == 1 local mtitle "`mtitle' `"TBA-eligible MBS"'"
}

esttab using "${table}/sumstat-within-high-balance.tex", label replace mtitle(`mtitle')  /// 
 stats(N, fmt(%9.0fc) label("N. Obs.")) collabels(, none) ///
 cell(mean(fmt(%9.2gc))) 
